import random
import string
from django.core.cache import cache
from django.core.mail import send_mail
from django.conf import settings

def generate_verification_code():
    """生成6位数字验证码"""
    return ''.join(random.choices(string.digits, k=6))

def send_verification_code(email, code):
    """发送验证码到邮箱"""
    subject = '重置密码验证码'
    message = f'您的验证码是：{code}，有效期为5分钟。如果这不是您的操作，请忽略此邮件。'
    from_email = settings.DEFAULT_FROM_EMAIL
    recipient_list = [email]
    
    try:
        send_mail(subject, message, from_email, recipient_list)
        return True
    except Exception as e:
        print(f"发送邮件失败: {e}")
        return False

def save_verification_code(email, code):
    """保存验证码到缓存，有效期5分钟"""
    cache_key = f'password_reset_{email}'
    cache.set(cache_key, code, timeout=300)  # 300秒 = 5分钟 TODO: why

def verify_code(email, code):
    """验证验证码是否正确"""
    cache_key = f'password_reset_{email}'
    saved_code = cache.get(cache_key)
    if saved_code and saved_code == code:
        # 验证成功后删除缓存的验证码
        cache.delete(cache_key)
        return True
    return False
